package com.token.service.impl;

import com.token.domain.LoginUser;
import com.token.domain.User;
import com.token.service.LoginService;
import com.token.utils.JwtUtil;
import com.token.utils.RedisCache;
import com.token.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public ResponseResult login(User user) {

       //AuthenticationManager 进行用户认证

//
//        UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword(),null);
////
//       Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//
        UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUserName());

        //如果认证通过了,使用userId生成一个jwt ,jwt存入ResponseResult返回

        if (Objects.isNull(userDetails)){
            throw new RuntimeException("登录失败");
        }

        //如果认证通过了，使用userId生成一个jwt，jwt存入ResponseResult返回
        System.out.println(userDetails);

        LoginUser loginUser= (LoginUser) userDetails;


        String userId =loginUser.getUser().getId().toString();


        JwtUtil.createJWT(userId);


        String jwt=JwtUtil.createJWT(userId);

        //把完整的用户信息存入redis ,userId作为key

       Map<String ,String> map=new HashMap<>();

       map.put("token",jwt);


        //把完整的用户信息存入redis userId作为key
        redisCache.setCacheObject("login:"+userId,loginUser);

        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {

        //获取SecurityContextHolder中的用户id

        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();


        LoginUser loginUser = (LoginUser) authentication.getPrincipal();



       Long userId= loginUser.getUser().getId();


       redisCache.deleteObject("login:"+userId);

        //删除redis中的值




        return new ResponseResult(200,"注销成功");
    }
}
